
// 客户服务地图小程序 后台接口(通用)

// csm_property  房地产项目数据 (projid, id, ...)
// csm_blog  新闻资讯 (projid, id, ...)
// csm_collection  收藏 (openid, activityids, mapids,...)
// csm_reservation  活动预约 (projid, id, ...)
// csm_reservation_pi  活动预约人员信息 （name;sex;proprietor;tel;address;hasBaby;babyName;babySex;babyAge;intention;community;email;isGroup）



const utils = require('../../utils/index.js');
const SqlHelper = utils.SqlHelper;

const routerApi = require('../../utils/routeString.js')(__filename, __dirname);



/**
 * @api {get} /csm_common_api?cmd=csm_reservation 获取活动报名数据
 * @apiDescription 根据projid与id获取活动报名数据
 * @apiGroup reservation
 * 
 * @apiParam {Object} where 
 * @apiParam {Number}  where.projid  每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  where.id  活动报名数据唯一ID.
 * 
 * @apiParam {Number} offset Optional（可选）如需分页，分页参数.
 * @apiParam {Number} limit Optional（可选）如需分页，分页参数.
 * 
 * @apiSuccess {Array} data 数据数组.
 * @apiSuccess {Array[]} data.dataItem data[0]元素.
 * 
 * @apiSuccess {Number} data.dataItem.projid 当前数据所属的程序项目.
 * @apiSuccess {Number} data.dataItem.id 当前数据的唯一ID.
 * @apiSuccess {String} data.dataItem.title 标题 .
 * @apiSuccess {String} data.dataItem.tel 电话 .
 * @apiSuccess {String} data.dataItem.address 地址 .
 * @apiSuccess {String} data.dataItem.text 活动详细说明 .
 * @apiSuccess {String} data.dataItem.time 活动时间 .
 * @apiSuccess {String} data.dataItem.fields 活动报名的字段 以";"分割.
 * @apiSuccess {Number} data.dataItem.pv 浏览量 .
 
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 * 
 */

const getReservation = async function (req, res) {

    let body = req.query;

    try {

        let sqlHelper = new SqlHelper('csm_reservation');

        let result = await sqlHelper.asyncSelect(body.where || null, body.offset || null, body.limit || null);

        return res.send({ data: result });

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}

/**
 * @api {get} /csm_common_api?cmd=reserve 报名
 * @apiDescription 报名某一个活动
 * @apiGroup reservation
 * 
 * @apiParam {Number}  projid  每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  openid  用户openid.
 * @apiParam {Number}  reservation_id  活动报名数据唯一ID.
 * @apiParam {Number}  name  姓名.
 * @apiParam {Number}  sex  性别.
 * @apiParam {Number}  proprietor  是否为业主.
 * @apiParam {Number}  tel  电话.
 * @apiParam {Number}  address  地址.
 * @apiParam {Number}  hasBaby  是否带宝宝.
 * @apiParam {Number}  babyName  宝宝姓名.
 * @apiParam {Number}  babySex  宝宝性别.
 * @apiParam {Number}  babyAge  宝宝年龄.
 * @apiParam {Number}  intention  意向活动.
 * @apiParam {Number}  remark  备注.
 * @apiParam {Number}  community  所属社区.
 * @apiParam {Number}  email  邮箱.
 * @apiParam {Number}  isGroup  是否愿意进入活动群.
 * 
 * @apiSuccess {Number} state 报名成功.
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 * 
 */

const reserve = async function (req, res) {

    let body = req.query;

    try {

        let sqlHelper = new SqlHelper('csm_reservation_pi');

        let hasData = await sqlHelper.asyncCheckExist({ projid: body.projid, openid: body.openid, reservation_id: body.reservation_id })

        if (hasData) {
            let result = await sqlHelper.asyncUpdate(body);
        } else {
            let result = await sqlHelper.asyncInsert(body);
        }

        return res.send({ state: 1, msg: "报名成功" });

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}

/**
 * @api {get} /csm_common_api?cmd=csm_property 获取房地产项目数据
 * @apiDescription 根据projid与id获取房地产项目数据
 * @apiGroup CSM
 * 
 * @apiParam {Object} where 传入projid指定某一个小程序项目的所有房产资料，projid与id指定某一个房产项目资料.
 * @apiParam {Number}  where.projid  每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  where.id  地产项目数据唯一ID.
 * @apiParam {Number} offset Optional（可选）如需分页，分页参数.
 * @apiParam {Number} limit Optional（可选）如需分页，分页参数.
 * 
 * @apiSuccess {Array} data 数据数组.
 * @apiSuccess {Array[]} data.dataItem data[0]元素.
 * 
 * @apiSuccess {Number} data.dataItem.projid 当前数据所属的程序项目.
 * @apiSuccess {Number} data.dataItem.id 当前数据的唯一ID.
 * @apiSuccess {String} data.dataItem.type 地产项目类型，例如泊寓、三好等 .
 * @apiSuccess {String} data.dataItem.state 地产项目状态，例如待售、即将销售等 .
 * @apiSuccess {String} data.dataItem.title 标题 .
 * @apiSuccess {String} data.dataItem.address 地址 .
 * @apiSuccess {String} data.dataItem.text 详细资料 .
 * @apiSuccess {String} data.dataItem.longitude 经度 .
 * @apiSuccess {String} data.dataItem.latitude 纬度 .
 * @apiSuccess {String} data.dataItem.scale 缩放 .
 * @apiSuccess {String} data.dataItem.icon_url 图标 .
 * @apiSuccess {String} data.dataItem.img_url 展示图片 .
 * @apiSuccess {String} data.dataItem.tel 电话 .
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 * 
 */

const getProperty = async function (req, res) {

    let body = req.query;

    try {

        let sqlHelper = new SqlHelper('csm_property');

        let result = await sqlHelper.asyncSelect(body.where || null, body.offset || null, body.limit || null);

        return res.send({ data: result });

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}


/**
 * @api {get} http://api.juzhen05.com/api/csm_common_api?cmd=csm_blog  获取新闻资讯
 * @apiGroup CSM
 * @apiDescription 获取新闻资讯
 * 
 * @apiParam {Object}  where 传入projid指定某一个小程序项目的所有房产资料，projid与id指定某一个房产项目资料.
 * @apiParam {Number}  where.projid  每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  where.id  地产项目数据唯一ID.
 * @apiParam {Number}  where.is_banner  为1时是需要放在首页banner的资讯.
 * 
 * 
 * @apiParam {Number} offset （可选）如需分页，分页参数.
 * @apiParam {Number} limit （可选）如需分页，分页参数.
 * 
 * @apiSuccess {Array} data 数据数组.
 * @apiSuccess {Array[]} data.dataItem data[0]元素.
 * 
 * @apiSuccess {Number} data.dataItem.projid 当前数据所属的程序项目.
 * @apiSuccess {Number} data.dataItem.id 当前数据的唯一ID.
 * @apiSuccess {String} data.dataItem.title 标题 .
 * @apiSuccess {String} data.dataItem.text 详细资料 .
 * @apiSuccess {String} data.dataItem.img_url 展示图片 .
 * @apiSuccess {Bool} data.dataItem.is_banner 是否要展示到首页banner .
 * @apiSuccess {Number} data.dataItem.pv 浏览量 .

 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 */
const getBlog = async function (req, res) {

    let body = req.query;

    try {

        let sqlHelper = new SqlHelper('csm_blog');

        let result = await sqlHelper.asyncSelect(body.where); // 最新的在第一个

        return res.send({ data: result });

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }


}

// 获取个人收藏
/**
 * @api {get} http://api.juzhen05.com/api/csm_common_api?cmd=collection  获取个人收藏数据
 *
 * @apiGroup Collection
 * 
 * @apiParam {Object} where 必填，传入openid与projid获取某个人收藏信息.
 * @apiParam {Number}  where.projid  每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  where.openid 当前用户的openid
 * 
 * @apiSuccess {Object} data 数据数组.
 * @apiSuccess {Array} data.property_collection 用户收藏的所有房产项目.
 * @apiSuccess {Array} data.reservation_collection 用户收藏的所有预约活动.
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 */

const getCollection = async function (req, res) {

    let body = req.query;

    try {

        let sqlHelper = new SqlHelper('csm_collection');


        let resultP = [];
        let resultR = [];

        let result = await sqlHelper.asyncSelect(body.where, null, null);

        if (result.length > 0) {

            let pCollection = result[0].property_collection.split(";"); // 1;2;3;4;5
            let rCollection = result[0].property_collection.split(";");


            if (pCollection.length > 0) {
                let sqlHelper2 = new SqlHelper('csm_property');
                let allData = await sqlHelper2.asyncSelect();
                for (let i = 0; i < pCollection.length; i++) {
                    for (let j = 0; j < allData.length; j++) {
                        if (pCollection[i] == allData[j].id) {
                            resultP.push(allData[j]);
                        }
                    }
                }
            }

            if (rCollection.length > 0) {
                let sqlHelper3 = new SqlHelper('csm_reservation');
                let allData = await sqlHelper3.asyncSelect();
                for (let i = 0; i < rCollection.length; i++) {
                    for (let j = 0; j < allData.length; j++) {
                        if (rCollection[i] == allData[j].id) {
                            resultR.push(allData[j]);
                        }
                    }
                }
            }
            return res.send({ property_collection: resultP, reservation_collection: resultR });

        } else {
            return res.send({ data: [] });
        }

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}

/**
 * @api {get} http://api.juzhen05.com/api/csm_common_api?cmd=follow  收藏
 *
 * @apiGroup Collection
 * 
 * @apiParam {String}  openid 用户openid.
 * @apiParam {Number}  projid 每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  id     当前数据的id
 * @apiParam {String}  type   当前数据的类型。"property"为房地产类型项目数据，"reservation"为活动报名数据
 * 
 * @apiSuccess {Number} state 为1时成功.
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 */
const follow = async function (req, res) {

    let body = req.query;

    if (!body.openid) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.projid) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.id) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.type) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }

    try {

        if (body.type == "property") {

            let sqlHelper = new SqlHelper('csm_collection');
            let oldData = await sqlHelper.asyncSelect({
                openid: body.openid,
                projid: body.projid
            });

            let collection = oldData[0] ? oldData[0].property_collection : "";
            collection = collection ? collection + ";" + body.id : body.id;

            if (oldData.length <= 0) {
                let result = await sqlHelper.asyncInsert({
                    openid: body.openid,
                    projid: body.projid,
                    property_collection: collection
                });
            } else {
                let result = await sqlHelper.asyncUpdate({
                    openid: body.openid,
                    projid: body.projid
                }, { property_collection: collection });
            }

            return res.send({ state: 1 });

        } else if (body.type == "reservation") {

            let sqlHelper = new SqlHelper('csm_collection');
            let oldData = await sqlHelper.asyncSelect({
                openid: body.openid,
                projid: body.projid
            });
            let collection = oldData[0] ? oldData[0].reservation_collection : "";
            collection = collection ? collection + ";" + body.id : body.id;

            if (oldData.length <= 0) {
                let result = await sqlHelper.asyncInsert({
                    openid: body.openid,
                    projid: body.projid,
                    reservation_collection: collection
                });
            } else {
                let result = await sqlHelper.asyncUpdate({
                    openid: body.openid,
                    projid: body.projid
                }, { reservation_collection: collection });
            }

            return res.send({ state: 1 });

        } else {

            return res.send({ error_code: 1, msg: "错误类型" });

        }
    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}

// 取消收藏
/**
 * @api {get} http://api.juzhen05.com/api/csm_common_api?cmd=unfollow  取消收藏
 *
 * @apiGroup Collection
 * 
 * @apiParam {String}  openid 用户openid.
 * @apiParam {Number}  projid 每一个客户服务地图小程序都有一个唯一ID.
 * @apiParam {Number}  id     当前数据的id
 * @apiParam {String}  type   当前数据的类型。"property"为房地产类型项目数据，"reservation"为活动报名数据
 * 
 * @apiSuccess {Number} state 为1时成功.
 * 
 * @apiError  {Object} data 
 * @apiError  {Object} data.error_code  值为1，错误.
 * @apiError  {Object} data.msg  错误描述.
 */
const unFollow = async function (req, res) {

    let body = req.query;

    if (!body.openid) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.projid) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.id) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }
    if (!body.type) {
        return res.send({ error_code: 1, msg: '缺少openid，请刷新再试' });
    }


    try {

        if (body.type == "property") {

            let sqlHelper = new SqlHelper('csm_collection');
            let oldData = await sqlHelper.asyncSelect({
                openid: body.openid,
                projid: body.projid
            });

            let collectionArr = oldData[0].property_collection.split(';');

            for (let i = 0; i < collectionArr.length; i++) {
                if (collectionArr[i] == body.id) {
                    collectionArr.splice(i, 1);
                    break;
                }
            }

            let collection = collectionArr.join(";");

            let result = await sqlHelper.asyncUpdate({
                openid: body.openid,
                projid: body.projid
            }, { property_collection: collection });

            return res.send({ state: 1 });

        } else if (body.type == "reservation") {

            let sqlHelper = new SqlHelper('csm_collection');
            let oldData = await sqlHelper.asyncSelect({
                openid: body.openid,
                projid: body.projid
            });

            let collectionArr = oldData[0].reservation_collection.split(';');

            for (let i = 0; i < collectionArr.length; i++) {
                if (collectionArr[i] == body.id) {
                    collectionArr.splice(i);
                    break;
                }
            }

            let collection = collectionArr.join(";");

            let result = await sqlHelper.asyncUpdate({
                openid: body.openid,
                projid: body.projid
            }, { reservation_collection: collection });

        } else {

            return res.send({ error_code: 1, msg: "错误类型" });

        }

    } catch (error) {

        return res.send({ error_code: 1, msg: error.message });

    }

}


// 资讯PV
const blogPv = async function (req, res) {

    let sqlHelper = new SqlHelper('csm_blog');

    let result = await sqlHelper.asyncQuery('UPDATE csm_blog SET pv=pv+1 WHERE projid="' + req.query.projid + ' and id="' + req.query.id + '";');

    return res.send({ state: 1 });
}

// 活动PV
const reservationPv = async function (req, res) {

    let sqlHelper = new SqlHelper('csm_reservation');

    let result = await sqlHelper.asyncQuery('UPDATE csm_reservation SET pv=pv+1 WHERE projid="' + req.query.projid + ' and id="' + req.query.id + '";');

    return res.send({ state: 1 });
}

// 流量统计
server.get({ path: routerApi }, async function (req, res) {

    var query = req.query;

    let cmd = query.cmd;
    delete query.cmd;

    switch (cmd) {
        case 'csm_property':  // 
            getProperty(req, res);
            break;
        case 'csm_blog':  // 
            getBlog(req, res);
            break;
        case 'csm_reservation':  // 
            getReservation(req, res);
            break;
        // case 'reservation':  // 获取自己所有报名过的活动id（可以根据ID获取活动数据）
        //     getMyReservation(req, res);
        //     break;
        case 'reserve':  // 报名活动
            reserve(req, res);
            break;
        case 'collection':
            getCollection(req, res);  // 获取自己的收藏列表
            break;
        case 'follow':
            follow(req, res);  // 收藏
            break;
        case 'unfollow':
            unFollow(req, res);  // 取消收藏
            break;
        case 'blog_pv':
            blogPv(req, res);  // 浏览量处理
            break;
        case 'reservation_pv':
            reservationPv(req, res);  // 浏览量处理
            break;
        default:
            return res.send({ error_code: 1, msg: '无效请求, cmd参数出错' });
    }

})